<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Camera API Integration Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .test-section h3 {
            margin-top: 0;
            color: #333;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            margin-top: 10px;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .success {
            border-color: #28a745;
            background-color: #d4edda;
        }
        .error {
            border-color: #dc3545;
            background-color: #f8d7da;
        }
        .status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        .status.online {
            background: #28a745;
            color: white;
        }
        .status.offline {
            background: #dc3545;
            color: white;
        }
        .camera-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            margin: 5px 0;
        }
        .camera-name {
            font-weight: bold;
            color: #333;
        }
        .camera-details {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Camera API Integration Test</h1>
        <p>This page tests the integration between the Vue.js frontend and Python FastAPI backend.</p>
        
        <div class="test-section">
            <h3>1. Backend Connection Test</h3>
            <button onclick="testBackendConnection()">Test Backend Connection</button>
            <div id="connection-result" class="result"></div>
        </div>

        <div class="test-section">
            <h3>2. Camera List API Test</h3>
            <button onclick="testGetCameraList()">Get Camera List</button>
            <button onclick="testGetCameraStatistics()">Get Statistics</button>
            <div id="list-result" class="result"></div>
        </div>

        <div class="test-section">
            <h3>3. Camera CRUD Operations Test</h3>
            <button onclick="testCreateCamera()">Create Test Camera</button>
            <button onclick="testUpdateCamera()" id="update-btn" disabled>Update Camera</button>
            <button onclick="testDeleteCamera()" id="delete-btn" disabled>Delete Camera</button>
            <div id="crud-result" class="result"></div>
        </div>

        <div class="test-section">
            <h3>4. Data Format Compatibility Test</h3>
            <button onclick="testDataFormatConversion()">Test Data Format</button>
            <div id="format-result" class="result"></div>
        </div>

        <div class="test-section">
            <h3>5. Error Handling Test</h3>
            <button onclick="testErrorHandling()">Test Error Scenarios</button>
            <div id="error-result" class="result"></div>
        </div>
    </div>

    <script>
        let testCameraId = null;
        const API_BASE = '/dev-api/api/v1';

        // Utility function to make API requests
        async function apiRequest(url, options = {}) {
            const defaultOptions = {
                headers: {
                    'Content-Type': 'application/json',
                },
            };
            
            const finalOptions = { ...defaultOptions, ...options };
            
            try {
                const response = await fetch(url, finalOptions);
                const data = await response.json();
                
                return {
                    success: response.ok,
                    status: response.status,
                    data: data
                };
            } catch (error) {
                return {
                    success: false,
                    error: error.message
                };
            }
        }

        // Test backend connection
        async function testBackendConnection() {
            const resultDiv = document.getElementById('connection-result');
            resultDiv.textContent = 'Testing connection...';
            resultDiv.className = 'result';

            try {
                const result = await apiRequest(`${API_BASE}/cameras?page=1&size=1`);
                
                if (result.success) {
                    resultDiv.textContent = `✅ Backend connection successful!\nStatus: ${result.status}\nResponse: ${JSON.stringify(result.data, null, 2)}`;
                    resultDiv.className = 'result success';
                } else {
                    resultDiv.textContent = `❌ Backend connection failed!\nStatus: ${result.status}\nError: ${JSON.stringify(result.data, null, 2)}`;
                    resultDiv.className = 'result error';
                }
            } catch (error) {
                resultDiv.textContent = `❌ Connection error: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }

        // Test get camera list
        async function testGetCameraList() {
            const resultDiv = document.getElementById('list-result');
            resultDiv.textContent = 'Loading camera list...';
            resultDiv.className = 'result';

            const result = await apiRequest(`${API_BASE}/cameras`);
            
            if (result.success) {
                const cameras = result.data.items || result.data.data || [];
                let output = `✅ Camera list loaded successfully!\nTotal cameras: ${cameras.length}\n\n`;
                
                cameras.forEach((camera, index) => {
                    output += `Camera ${index + 1}:\n`;
                    output += `  ID: ${camera.id}\n`;
                    output += `  Name: ${camera.name}\n`;
                    output += `  Status: ${camera.status}\n`;
                    output += `  Location: ${camera.longitude}, ${camera.latitude}\n`;
                    output += `  RTSP: ${camera.rtsp_url || 'Not set'}\n\n`;
                });
                
                resultDiv.textContent = output;
                resultDiv.className = 'result success';
            } else {
                resultDiv.textContent = `❌ Failed to load camera list\nError: ${JSON.stringify(result.data || result.error, null, 2)}`;
                resultDiv.className = 'result error';
            }
        }

        // Test get camera statistics
        async function testGetCameraStatistics() {
            const resultDiv = document.getElementById('list-result');
            resultDiv.textContent = 'Loading statistics...';
            resultDiv.className = 'result';

            const result = await apiRequest(`${API_BASE}/cameras/statistics/summary`);
            
            if (result.success) {
                const stats = result.data;
                const output = `✅ Statistics loaded successfully!\n${JSON.stringify(stats, null, 2)}`;
                resultDiv.textContent = output;
                resultDiv.className = 'result success';
            } else {
                resultDiv.textContent = `❌ Failed to load statistics\nError: ${JSON.stringify(result.data || result.error, null, 2)}`;
                resultDiv.className = 'result error';
            }
        }

        // Test create camera
        async function testCreateCamera() {
            const resultDiv = document.getElementById('crud-result');
            resultDiv.textContent = 'Creating test camera...';
            resultDiv.className = 'result';

            const testCamera = {
                name: `Test Camera ${Date.now()}`,
                longitude: 113.8720 + (Math.random() - 0.5) * 0.01,
                latitude: 27.6303 + (Math.random() - 0.5) * 0.01,
                height: 15,
                location: 'Test Location',
                rtsp_url: 'rtsp://test.example.com/stream1',
                wvp_device_id: 'TEST_DEVICE_001',
                wvp_channel_id: 'TEST_CHANNEL_001',
                description: 'Test camera created by API integration test',
                ai_enabled: true
            };

            const result = await apiRequest(`${API_BASE}/cameras`, {
                method: 'POST',
                body: JSON.stringify(testCamera)
            });
            
            if (result.success) {
                testCameraId = result.data.id;
                document.getElementById('update-btn').disabled = false;
                document.getElementById('delete-btn').disabled = false;
                
                resultDiv.textContent = `✅ Camera created successfully!\nCamera ID: ${testCameraId}\nResponse: ${JSON.stringify(result.data, null, 2)}`;
                resultDiv.className = 'result success';
            } else {
                resultDiv.textContent = `❌ Failed to create camera\nError: ${JSON.stringify(result.data || result.error, null, 2)}`;
                resultDiv.className = 'result error';
            }
        }

        // Test update camera
        async function testUpdateCamera() {
            if (!testCameraId) {
                alert('Please create a test camera first');
                return;
            }

            const resultDiv = document.getElementById('crud-result');
            resultDiv.textContent = 'Updating test camera...';
            resultDiv.className = 'result';

            const updateData = {
                name: `Updated Test Camera ${Date.now()}`,
                description: 'Updated description by API test',
                ai_enabled: false
            };

            const result = await apiRequest(`${API_BASE}/cameras/${testCameraId}`, {
                method: 'PUT',
                body: JSON.stringify(updateData)
            });
            
            if (result.success) {
                resultDiv.textContent = `✅ Camera updated successfully!\nResponse: ${JSON.stringify(result.data, null, 2)}`;
                resultDiv.className = 'result success';
            } else {
                resultDiv.textContent = `❌ Failed to update camera\nError: ${JSON.stringify(result.data || result.error, null, 2)}`;
                resultDiv.className = 'result error';
            }
        }

        // Test delete camera
        async function testDeleteCamera() {
            if (!testCameraId) {
                alert('Please create a test camera first');
                return;
            }

            const resultDiv = document.getElementById('crud-result');
            resultDiv.textContent = 'Deleting test camera...';
            resultDiv.className = 'result';

            const result = await apiRequest(`${API_BASE}/cameras/${testCameraId}`, {
                method: 'DELETE'
            });
            
            if (result.success) {
                resultDiv.textContent = `✅ Camera deleted successfully!\nCamera ID: ${testCameraId}`;
                resultDiv.className = 'result success';
                
                testCameraId = null;
                document.getElementById('update-btn').disabled = true;
                document.getElementById('delete-btn').disabled = true;
            } else {
                resultDiv.textContent = `❌ Failed to delete camera\nError: ${JSON.stringify(result.data || result.error, null, 2)}`;
                resultDiv.className = 'result error';
            }
        }

        // Test data format conversion
        async function testDataFormatConversion() {
            const resultDiv = document.getElementById('format-result');
            resultDiv.textContent = 'Testing data format conversion...';
            resultDiv.className = 'result';

            // Test frontend format to backend format conversion
            const frontendData = {
                name: 'Format Test Camera',
                position: {
                    longitude: 113.8720,
                    latitude: 27.6303,
                    height: 15
                },
                rtspUrl: 'rtsp://test.example.com/stream1',
                deviceId: 'TEST_DEVICE',
                channelId: 'TEST_CHANNEL',
                aiEnabled: true
            };

            // Convert to backend format (simulating the conversion in camera.js)
            const backendData = {
                name: frontendData.name,
                longitude: frontendData.position.longitude,
                latitude: frontendData.position.latitude,
                height: frontendData.position.height,
                rtsp_url: frontendData.rtspUrl,
                wvp_device_id: frontendData.deviceId,
                wvp_channel_id: frontendData.channelId,
                ai_enabled: frontendData.aiEnabled
            };

            let output = '✅ Data format conversion test:\n\n';
            output += 'Frontend format:\n';
            output += JSON.stringify(frontendData, null, 2);
            output += '\n\nBackend format:\n';
            output += JSON.stringify(backendData, null, 2);
            output += '\n\n✅ Conversion successful!';

            resultDiv.textContent = output;
            resultDiv.className = 'result success';
        }

        // Test error handling
        async function testErrorHandling() {
            const resultDiv = document.getElementById('error-result');
            resultDiv.textContent = 'Testing error handling scenarios...';
            resultDiv.className = 'result';

            let output = 'Error Handling Tests:\n\n';

            // Test 1: Invalid camera ID
            try {
                const result1 = await apiRequest(`${API_BASE}/cameras/99999`);
                output += `1. Invalid camera ID test:\n`;
                output += `   Status: ${result1.status}\n`;
                output += `   Response: ${JSON.stringify(result1.data, null, 2)}\n\n`;
            } catch (error) {
                output += `1. Invalid camera ID test: Error - ${error.message}\n\n`;
            }

            // Test 2: Invalid data format
            try {
                const result2 = await apiRequest(`${API_BASE}/cameras`, {
                    method: 'POST',
                    body: JSON.stringify({ invalid: 'data' })
                });
                output += `2. Invalid data format test:\n`;
                output += `   Status: ${result2.status}\n`;
                output += `   Response: ${JSON.stringify(result2.data, null, 2)}\n\n`;
            } catch (error) {
                output += `2. Invalid data format test: Error - ${error.message}\n\n`;
            }

            // Test 3: Non-existent endpoint
            try {
                const result3 = await apiRequest(`${API_BASE}/nonexistent`);
                output += `3. Non-existent endpoint test:\n`;
                output += `   Status: ${result3.status}\n`;
                output += `   Response: ${JSON.stringify(result3.data, null, 2)}\n\n`;
            } catch (error) {
                output += `3. Non-existent endpoint test: Error - ${error.message}\n\n`;
            }

            output += '✅ Error handling tests completed!';
            resultDiv.textContent = output;
            resultDiv.className = 'result success';
        }

        // Auto-run connection test on page load
        window.addEventListener('load', () => {
            setTimeout(testBackendConnection, 1000);
        });
    </script>
</body>
</html>